package authentication

import (
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/cache"
	"gitee.com/Luna-CY/hui-hui/internal/configure"
	"gitee.com/Luna-CY/hui-hui/internal/util/smtp"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"math/rand"
	"strings"
	"time"
)

func (cls *Authentication) SendLoginCode(_ *gin.Context) (int, any, error) {
	if "" == configure.Configure.Smtp.Host || 0 == configure.Configure.Smtp.Port {
		return response.Ok, nil, nil
	}

	if configure.AuthenticationTypeEmailCode == configure.Configure.Server.Authentication.Type && "" != configure.Configure.Server.Authentication.Email {
		var code = new(strings.Builder)
		for i := 0; i < 6; i++ {
			code.WriteString(fmt.Sprintf("%d", rand.Intn(10)))
		}

		if err := cache.GetCache().Set(cache.AuthorizationCode, code.String(), 15*time.Minute); nil != err {
			return response.Unknown, nil, err
		}

		if err := smtp.SendLoginCode(configure.Configure.Server.Authentication.Email, code.String()); nil != err {
			return response.Unknown, nil, err
		}
	}

	return response.Ok, nil, nil
}
